package net.thxjj.mobileServer.util;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.iot.client.AWSIotException;
import com.amazonaws.services.iot.client.AWSIotMqttClient;
import com.amazonaws.services.iot.client.AWSIotTopic;
import net.thxjj.mobileServer.entity.DataBean;
import net.thxjj.mobileServer.util.sampleUtil.NonBlockingPublisher;
import net.thxjj.mobileServer.util.sampleUtil.SampleUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @since 2017-08-18
 * @author tyro
 *
 */
public class Tools {
	private static Logger log = Logger.getLogger("Tools");
	private static AWSIotMqttClient awsIotClient;
	/**
	 * 返回随机数
	 * 
	 * @param n 个数
	 * @return
	 */
	public static String random(int n) {
		if (n < 1 || n > 10) {
			throw new IllegalArgumentException("cannot random " + n + " bit number");
		}
		Random ran = new Random();
		if (n == 1) {
			return String.valueOf(ran.nextInt(10));
		}
		int bitField = 0;
		char[] chs = new char[n];
		for (int i = 0; i < n; i++) {
			while (true) {
				int k = ran.nextInt(10);
				if ((bitField & (1 << k)) == 0) {
					bitField |= 1 << k;
					chs[i] = (char) (k + '0');
					break;
				}
			}
		}
		return new String(chs);
	}

	/**
	 * 指定范围的随机数
	 * 
	 * @param min
	 *            最小值
	 * @param max
	 *            最大值
	 * @return
	 */
	public static int getRandomNum(int min, int max) {
		Random random = new Random();
		int s = random.nextInt(max) % (max - min + 1) + min;
		return s;
	}

	/**
	 * 检测字符串是否不为空(null,"","null")
	 * 
	 * @param s
	 * @return 不为空则返回true，否则返回false
	 */
	public static boolean notEmpty(String s) {
		return s != null && !"".equals(s) && !"null".equals(s);
	}

	/**
	 * 检测字符串是否为空(null,"","null")
	 * 
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(String s) {
		return s == null || "".equals(s) || "null".equals(s);
	}
	
	/**
	 * 检测是否为数字
	 * @param s
	 * @return
	 */
	public static boolean isNumber(String s) {
		try {
			Integer.parseInt(s);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	public static boolean isEmail(String email) {

		Pattern emailPattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

		Matcher matcher = emailPattern.matcher(email);

		if(matcher.find()){

			return true;

		}

		return false;

	}

	public static boolean isRegisterUserNameLegal(String username) {

		Pattern emailPattern = Pattern.compile("[a-f0-9]{32}");

		Matcher matcher = emailPattern.matcher(username);

		if(matcher.find()){

			return true;

		}

		return false;

	}


	/**
	 * 检测是否为数字
	 * @param length
	 * @return
	 */
	public static String randomCharData(int length){
		StringBuilder sb = new StringBuilder();
		Random rand = new Random();
		Random randdata = new Random();

		int data = 0;
		for(int i=0;i<length;i++)
		{
			int index = rand.nextInt(2);
			switch (index){
				case 0:
					data = randdata.nextInt(10);
					sb.append(data);
					break;
				case 1:
					data = randdata.nextInt(26)+97;
					sb.append((char)data);
					break;
			}
		}



		return sb.toString();
	}

	public static void main(String[] args) {
//		String clientEndpoint = SampleUtil.getConfig("clientEndpoint");
//		String clientId = SampleUtil.getConfig("clientId");
//
//		String certificateFile = SampleUtil.getConfig("certificateFile");
//		String privateKeyFile = SampleUtil.getConfig("privateKeyFile");
//		if (awsIotClient == null && certificateFile != null && privateKeyFile != null) {
//			String algorithm = SampleUtil.getConfig("keyAlgorithm");
//			SampleUtil.KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile, algorithm);
//
//			awsIotClient = new AWSIotMqttClient(clientEndpoint, clientId, pair.keyStore, pair.keyPassword);
//		}
//
//		try {
//			awsIotClient.connect();
//		} catch (AWSIotException e) {
//			e.printStackTrace();
//		}
//
//		String aa = "{\"hw_id\":\"000c2933eaa6\",\"msg\":{\"CMD_CODE\":1,\"str1\":\"3769000603\",\"str2\":\"010D01\",\"str3\":\"\"},\"msg_id\":13,\"namespace\":\"config\",\"source\":\"app\",\"target\":\"gateway\"}";
//
//		DataBean dataBean = JSONObject.parseObject(aa,DataBean.class);
//
//
//
//		Thread blockingPublishThread = new Thread(new NonBlockingPublisher(awsIotClient,dataBean));
//		blockingPublishThread.start();

		String url="https://api.amazon.com/auth/o2/token";
		String sync = OkHttpUtils.builder().url(url)
				// 请求参数可以添加多个参数
				.addParam("grant_type", "refresh_token")
				.addParam("refresh_token", "Atzr|IwEBINHQVBhryKVpHpYqcjk5lEr89QmssPjt5TskR7VqRMSU9K4xAm22wwps8t-LITsiehKVXSgTFUIvE9ILrqcNqdMEw7IgX8r2ogIcOrWKfSs_HXq-EPH82PxmPRCIhxrF8yFKUsxdkLRtnN85NNrYdN0VwdN_cFreegut6Urt2SWkUNzR0iXmyfy9GpkxSQ9I1AUGdQUDUPXWKE16Nn9k4tUxPobpHQdMwJtNwIfLi8M6zUrbDG_9I4CbRALwdurCBz_yC52ZIR3Aav6wXzsuIE3q")
				.addParam("client_id", "amzn1.application-oa2-client.9f50b774724d4dbe801aef293f4bf6b3")
				.addParam("client_secret","6782e8c8ba04f74fc831ac37cdab4a8b9bfe77866fdf9083fd7a586a55497b8c")
				// 也可以添加多个请求读数据
				.post(false)
				// 支持同步请求还是异步请求
				//.async(); //异步
				.sync();//同步

		log.info("==sync:"+sync);


	}



}
